<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="城市" prop="city">
              <el-input v-model="queryParams.city" placeholder="请输入城市" clearable @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model="queryParams.phone" placeholder="请输入电话" clearable @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['app:SkDailiShengqing:add']">新增</el-button>-->
          <!--          </el-col>-->
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
                       v-hasPermi="['app:SkDailiShengqing:edit']">修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
                       v-hasPermi="['app:SkDailiShengqing:remove']">删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
                       v-hasPermi="['app:SkDailiShengqing:export']">导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="SkDailiShengqingList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="ID" align="center" prop="id" width="180" v-if="true"/>
        <el-table-column label="姓名" align="center" prop="name"/>
        <el-table-column label="城市" align="center" prop="city"/>
        <el-table-column label="电话" align="center" prop="phone"/>
        <el-table-column label="行业认知" align="center" prop="industryAwareness">
          <template #default="props">
            <el-tag style="margin-left: 10px;" v-if="props.row.industryAwareness"
                    v-for="(item, index) in props.row.industryAwareness.split(',')" type="primary">{{ item }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="state">
          <template #default="scope">
            <el-tag type="primary" v-if="scope.row.state == 0">待审核</el-tag>
            <el-tag type="success" v-if="scope.row.state == 1">已同意</el-tag>
            <el-tag type="warning" v-if="scope.row.state == 2">已拒绝</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="通过" placement="top" v-if="scope.row.state==0">
              <el-button link type="primary" icon="Check" @click="handleUpdateTongguo(scope.row)"
                         v-hasPermi="['app:SkDailiShengqing:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="拒绝" placement="top" v-if="scope.row.state==0">
              <el-button link type="primary" icon="Close" @click="handleUpdateJujue(scope.row)"
                         v-hasPermi="['app:SkDailiShengqing:edit']"></el-button>
            </el-tooltip>
            <!--            <el-tooltip content="修改" placement="top">-->
            <!--              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['app:SkDailiShengqing:edit']"></el-button>-->
            <!--            </el-tooltip>-->
            <!--            <el-tooltip content="删除" placement="top">-->
            <!--              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['app:SkDailiShengqing:remove']"></el-button>-->
            <!--            </el-tooltip>-->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                  v-model:limit="queryParams.pageSize" @pagination="getList"/>
    </el-card>
    <!-- 添加或修改代理申请信息对话框 -->
    <!--    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>-->
    <!--      <el-form ref="SkDailiShengqingFormRef" :model="form" :rules="rules" label-width="80px">-->
    <!--        <div>是否确认审核通过城市【{{form.city}}】的代理？</div><br>-->
    <!--        <div style="font-size: 12px;color: #fdd200">注：每个城市只有一个代理！</div>-->
    <!--      </el-form>-->
    <!--      <template #footer>-->
    <!--        <div class="dialog-footer">-->
    <!--          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>-->
    <!--          <el-button @click="cancel">取 消</el-button>-->
    <!--        </div>-->
    <!--      </template>-->
    <!--    </el-dialog>-->

    <el-dialog :title="dialog.title2" v-model="dialog.visible2" width="500px" append-to-body>
      <el-form ref="SkDailiShengqingFormRef" :model="form" :rules="rules" label-width="80px">
        <div>是否确认拒绝城市【{{ form.city }}】的代理？</div>
        <br>
        <div style="font-size: 12px;color: #fdd200">注：拒绝后不可更改！</div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog ref="formDialogRef" v-model="dialog.visible" :title="dialog.title" width="700px" append-to-body
               @close="closeDialog">
      <el-form ref="userFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item  label="用户名称" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户名称" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入用户密码" type="password" maxlength="20"
                        show-password/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="申请城市">
              <el-input v-model="form.city" disabled placeholder="请输入城市区号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分配城市">
              <div style="display: flex">
                <el-input v-model="form.cityTitle" disabled placeholder="请选择城市"></el-input>
                <el-button style="margin-left: 10px" @click="selectCity=true">选择城市</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="tgsubmitForm">确 定</el-button>
          <el-button @click="cancel()">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--    城市选择-->
    <el-drawer
      v-model="selectCity"
      title="选择代理城市"
      direction="rtl"
      size="50%"
    >
      <div class="city-list">
        <div style="display: flex;margin-bottom: 10px">
          <el-input style="margin-right: 20px" type="text" v-model="search"/>
          <el-button type="primary" @click="toTarget('#' + search)">搜索</el-button>
        </div>
        <div v-for="(item,index) in list">
          <div style="font-weight: bold;font-size: 18px;margin-bottom: 10px">{{item.initial}}</div>
          <div style="display: flex;flex-wrap: wrap" >
            <div :id="info.name" style="margin-left: 10px;margin-bottom: 10px;border-radius: 8px" v-for="info in item.list">
              <el-button @click="selectTrueCuty(info)">{{info.name}}</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup name="SkDailiShengqing" lang="ts">
import {
  listSkDailiShengqing,
  getSkDailiShengqing,
  delSkDailiShengqing,
  addSkDailiShengqing,
  updateSkDailiShengqing
} from '@/api/app/SkDailiShengqing';
import {SkDailiShengqingVO, SkDailiShengqingQuery, SkDailiShengqingForm} from '@/api/app/SkDailiShengqing/types';
import city from '@/views/app/SkDailiShengqing/city'
import { provinceAndCityData, codeToText } from 'element-china-area-data'
import api from "@/api/system/user";
const options = provinceAndCityData;
const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const list = city.city;
const selectCity = ref(false);
const SkDailiShengqingList = ref<SkDailiShengqingVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const search = ref('');
const queryFormRef = ref<ElFormInstance>();
const SkDailiShengqingFormRef = ref<ElFormInstance>();
const dailiform = ref({
  userId: undefined,
  deptId: '1821056019675574274',
  userName: '',
  nickName: undefined,
  password: '',
  phonenumber: undefined,
  email: undefined,
  sex: undefined,
  city:undefined,
  sqCity:undefined,
  status: '0',
  remark: '',
  postIds: [],
  roleIds: ['1850713515750948866']
});
const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
  visible2: false,
  title2: ''
});

const initFormData: SkDailiShengqingForm = {
  id: undefined,
  name: undefined,
  city: undefined,
  phone: undefined,
  userId: undefined,
  industryAwareness: undefined,
  cityCode:undefined,
  userName: undefined,
  password: undefined,
  roleIds: ['1850713515750948866'],
  deptId: '1821056019675574274',
}
const data = reactive<PageData<SkDailiShengqingForm, SkDailiShengqingQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    city: undefined,
    phone: undefined,
    industryAwareness: undefined,
    params: {}
  },
  rules: {
    id: [
      {required: true, message: "ID不能为空", trigger: "blur"}
    ],
    name: [
      {required: true, message: "姓名不能为空", trigger: "blur"}
    ],
    city: [
      {required: true, message: "城市不能为空", trigger: "blur"}
    ],
    phone: [
      {required: true, message: "电话不能为空", trigger: "blur"}
    ],
    industryAwareness: [
      {required: true, message: "行业认知不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询代理申请信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSkDailiShengqing(queryParams.value);
  SkDailiShengqingList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  dialog.visible2 = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  SkDailiShengqingFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: SkDailiShengqingVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加代理申请信息";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: SkDailiShengqingVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getSkDailiShengqing(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改代理申请信息";
}

/** 修改按钮操作 */
const handleUpdateTongguo = async (row?: SkDailiShengqingVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getSkDailiShengqing(_id);
  Object.assign(form.value, res.data);
  form.value.state = 1
  dailiform.value.sqCity = row.city
  dialog.visible = true;
  dialog.title = "通过代理申请信息";
}

/** 修改按钮操作 */
const handleUpdateJujue = async (row?: SkDailiShengqingVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getSkDailiShengqing(_id);
  Object.assign(form.value, res.data);
  form.value.state = 2
  dialog.visible2 = true;
  dialog.title2 = "拒绝代理申请信息";
}

/** 提交按钮 */
const submitForm = async () => {
  console.log("1111111111")
  form.value.cityCode = dailiform.value.remark
  const res = await updateSkDailiShengqing(form.value).finally(() => {
    console.log("111111122222222211111111");
    buttonLoading.value = false
  })
  console.log(res,"11111111")
  // SkDailiShengqingFormRef.value?.validate(async (valid: boolean) => {
  //   if (valid) {
  //     buttonLoading.value = true;
  //     if (form.value.id) {
  //       await updateSkDailiShengqing(form.value).finally(() => {
  //           console.log("111111111111111");
  //           buttonLoading.value = false
  //       }
  //       );
  //     } else {
  //       await addSkDailiShengqing(form.value).finally(() => buttonLoading.value = false);
  //     }
  //     proxy?.$modal.msgSuccess("操作成功");
  //     dialog.visible = false;
  //     dialog.visible2 = false;
  //     await getList();
  //   }
  // });
}

/** 删除按钮操作 */
const handleDelete = async (row?: SkDailiShengqingVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除代理申请信息编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delSkDailiShengqing(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('app/SkDailiShengqing/export', {
    ...queryParams.value
  }, `SkDailiShengqing_${new Date().getTime()}.xlsx`)
}
const toTarget = (target)=> {
  console.log(target)
  const toElement = document.querySelector(target) // 获取文档中 id="demo" 的元素：
  console.log(toElement)
  toElement.scrollIntoView()
}
//确认选择城市
const selectTrueCuty = (info) =>{
  console.log(info)
  selectCity.value = false
  form.value.cityCode = info.code
  form.value.cityTitle = info.name+"["+info.code+"]"
}
//提交申请通过
/** 提交按钮 */
const tgsubmitForm = async () => {
  await submitForm()

};
onMounted(() => {

  getList();
});
</script>
